package com.company.sort;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Random;

/**
 * @author shenhan
 * @create 2020/1/29 17:46
 * @description
 */
public class BubbleSort {
    public static void main(String[] args) {
        // 测试8000个数据
        int[] arr = new int[80000];
        Random random = new Random();
        for (int i = 0; i < 80000; i++) {
            arr[i] = random.nextInt();
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date time1 = new Date();
        System.out.println(simpleDateFormat.format(time1));
        bubbleSort(arr);
        Date time2 = new Date();
        System.out.println(simpleDateFormat.format(time2));
        /*int[] arr = {3, 9, -1, 10, 20};
        bubbleSort(arr);*/
        /*// 第一次排序
        for (int i = 0; i < arr.length - 1; i++) {
            if (arr[i] > arr[i + 1]) {
                temp = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = temp;
            }
        }
        System.out.println("第一次排序过后");
        System.out.println(Arrays.toString(arr));
        // 第2次排序
        for (int i = 0; i < arr.length - 2; i++) {
            if (arr[i] > arr[i + 1]) {
                temp = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = temp;
            }
        }
        System.out.println("第2次排序过后");
        System.out.println(Arrays.toString(arr));

        // 第3次排序
        for (int i = 0; i < arr.length - 3; i++) {
            if (arr[i] > arr[i + 1]) {
                temp = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = temp;
            }
        }
        System.out.println("第3次排序过后");
        System.out.println(Arrays.toString(arr));

        // 第4次排序
        for (int i = 0; i < arr.length - 4; i++) {
            if (arr[i] > arr[i + 1]) {
                temp = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = temp;
            }
        }
        System.out.println("第4次排序过后");
        System.out.println(Arrays.toString(arr));*/
    }

    private static void bubbleSort(int[] arr) {
        int temp;
        boolean flag = false;
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = 0; j < arr.length - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    flag = true;
                    temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
//            System.out.printf("第%d次排序过后\n", i + 1);
//            System.out.println(Arrays.toString(arr));
            if (!flag) {
                break;
            } else {
                flag = false;
            }
        }
    }
}
